﻿
import paho.mqtt.client as mqtt
from aip import AipFace
from picamera import PiCamera
import urllib.request
#import RPi.GPIO as GPIO
import base64
import time
#百度人脸识别API账号信息
APP_ID = '16579110'
API_KEY = 'aXSuuPjWlVpqtrShLqvOmt1L'
SECRET_KEY ='你自己的key'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)#创建一个客户端用以访问百度云
#图像编码方式
IMAGE_TYPE='BASE64'
camera = PiCamera()#定义一个摄像头对象
#用户组
GROUP = '1'
#GPIO_IN_PIN = 15
#GPIO_OUT_PIN1 = 11
#GPIO_OUT_PIN2 = 13
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))

def on_message(client, userdata, msg):
  print(msg.topic+" "+str(msg.payload))

client1 = mqtt.Client()
client1.on_connect = on_connect
client1.on_message = on_message
client1.connect("自己的mqtt服务器", 1883, 600)
#照相函
def getimage():
    camera.resolution = (1024,768)
    camera.start_preview()
    time.sleep(2)
    camera.capture('faceimage.jpg')
    time.sleep(2)

#对图片的格式进行转换
def transimage():
    f = open('faceimage.jpg','rb')
    img = base64.b64encode(f.read())
    return img
#上传到百度api进行人脸检测
def go_api(image):
    result = client.search(str(image, 'utf-8'), IMAGE_TYPE, GROUP);
    if result['error_msg'] == 'SUCCESS':
        name = result['result']['user_list'][0]['user_id']
        score = result['result']['user_list'][0]['score']
        if score > 80:
            print("Welcome %s !" % name)
            if name == '1':
               print("欢迎%s !" % name)
               time.sleep(3)
           
               
            
        else:
            print("Sorry...I don't know you !")
            
            name = 'Unknow'
            return 0
        curren_time = time.asctime(time.localtime(time.time()))
        f = open('Log.txt','a')
        f.write("Person: " + name + "     " + "Time:" + str(curren_time)+'\n')
        f.close()
        return 1
    if result['error_msg'] == 'pic not has face':
        print('There is no face in image!')
        
        time.sleep(2)
        return 0
   # else:
       # print(result['error_code']+' ' + result['error_code'])
       # return 0
#主函数
if __name__ == '__main__':
    #GPIO.setmode(GPIO.BOARD)
    #GPIO.setup(GPIO_IN_PIN,GPIO.IN)
    #GPIO.setup(GPIO_OUT_PIN1,GPIO.OUT)
    #GPIO.setup(GPIO_OUT_PIN2,GPIO.OUT)
    while True:
        print('OK')
        if True:
        #if GPIO.input(GPIO_IN_PIN) == GPIO.LOW:
            getimage()
            img = transimage()
            res = go_api(img)
            if(res == 1):
                 print("开门")
                 client1.publish('xingeju',payload='6',qos=0)
                 time.sleep(1)
               # GPIO.output(GPIO_OUT_PIN2,GPIO.LOW)
            else:
                print("关门")
                print('稍等三秒进入下一个')
               
                time.sleep(1)
               # GPIO.output(GPIO_OUT_PIN1,GPIO.LOW)
           
        
            time.sleep(3)
           





